package org.example.websockettest.service.impl;

import org.example.websockettest.param.DataMessage;
import org.example.websockettest.service.interfaces.RedisService;
import org.example.websockettest.utils.JsonRedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class RedisServiceImpl implements RedisService {

    private static final String ONLINE_USERS_KEY = "online_users";
    private static final String OFFLINE_MESSAGES_KEY_PREFIX = "offline_messages:";

    @Autowired
    private JsonRedisTemplate redisTemplate;

    @Override
    public void addUser(String username) {
        redisTemplate.opsForSet().add(ONLINE_USERS_KEY, username);
    }

    @Override
    public void removeUser(String username) {
        redisTemplate.opsForSet().remove(ONLINE_USERS_KEY, username);
    }

    @Override
    public Set<Object> getOnlineUsers() {
        return redisTemplate.opsForSet().members(ONLINE_USERS_KEY);
    }

    @Override
    public long getOnlineUserCount() {
        return redisTemplate.opsForSet().size(ONLINE_USERS_KEY);
    }

    @Override
    public boolean isUserOnline(String username) {
        return redisTemplate.opsForSet().isMember(ONLINE_USERS_KEY, username);
    }

    @Override
    public void clearOnlineUsers() {
        redisTemplate.delete(ONLINE_USERS_KEY);
    }

    public void storeOfflineMessage(String username, DataMessage message) {
        redisTemplate.opsForList().rightPush(OFFLINE_MESSAGES_KEY_PREFIX + username, message);
    }

    public List<Object> getOfflineMessages(String username) {
        return redisTemplate.opsForList().range(OFFLINE_MESSAGES_KEY_PREFIX + username, 0, -1);
    }

    public void clearOfflineMessages(String username) {
        redisTemplate.delete(OFFLINE_MESSAGES_KEY_PREFIX + username);
    }
}
